package com.qf.bookks.interceptor;

import com.qf.bookks.utils.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("请求进入拦截器了,请求的url={}",request.getRequestURI());

        // 判断用户的登录状态 ，约定，如果session中有key user，并且value不为null，代表该浏览器曾经登录过
        final HttpSession session = request.getSession();
        final Object user = session.getAttribute(Constants.USER_LOGIN_SESSION_KEY);

        if (user!=null){
            // 登录过,放行
            log.debug("请求被放行了");
            return true;
        }
        log.debug("请求被拦截了,重定向到 登录页");
        // 让浏览器重定向到 /login.html
        response.sendRedirect("/login.html");
        return false;
    }
}
